package com.pig4cloud.util;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.pig4cloud.entity.UserEntity;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Author: oliver
 * @CreateTime: 2023-02-24
 * @Description: 小程序权限工具类
 * @Version: 1.0
 */
public class AuthUtil {

	public static UserEntity getUser() {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
		if (request == null) {
			return new UserEntity();
		} else {
			Object tbUser = request.getAttribute("_MINI_USER_REQUEST_ATTR_");
			if (tbUser == null) {
				tbUser = getUser(request);
				if (tbUser != null) {
					request.setAttribute("_MINI_USER_REQUEST_ATTR_", tbUser);
				}
			}

			return (UserEntity) tbUser;
		}
	}

	public static UserEntity getUser(HttpServletRequest request) {
		return getUserEntity(request);
	}

	public static UserEntity getUserEntity(HttpServletRequest request) {
		String header = request.getHeader(CommonConstants.LOGIN_TOKEN_KEY);
		UserEntity tbUser;
		String token;
		if (StringUtil.isNotBlank(header)) {
			token = header;
		} else {
			return null;
		}
		tbUser = JwtUtil.parseToken(token);

		if (ObjectUtil.isNotEmpty(tbUser)) {
			return tbUser;
		}
		return null;
	}
}
